import React, { useRef, useEffect, useCallback } from 'react';
import { message } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { ModalPro, FormPro } from '@/components';
import { CloneProps } from '@/components/ModalPro';
import { FormItem } from '@/components/FormPro/types';
import addService from '@/service/article/add';
import editService from '@/service/article/edit';

type ProxyProps = {
  data?: any;
  children: React.ReactElement;
  onSuccess(): void;
}

type IProps = Omit<ProxyProps, 'children'> & CloneProps;

const formList: FormItem[] = [
  {
    type: 'input',
    name: 'title',
    label: '文章标题',
    rules: [{ required: true, message: '请输入标题' }],
  },
  {
    type: 'upload',
    name: 'banner',
    label: 'banner图',
    rules: [{ required: true, message: '请上传banner图' }],
  },
  {
    type: 'textArea',
    name: 'simpleContent',
    label: '简略内容',
    rules: [{ required: true, message: '请输入简略内容' }],
  },
  {
    type: 'editor',
    name: 'content',
    label: '正文内容',
    rules: [{ required: true, message: '请输入正文内容' }],
  },
];

const EditPage: React.FC<IProps> = props => {
  const {
    data,
    listenOk,
    submitStop,
    onSuccess,
    closeModal,
    submitLoading
  } = props;

  const formRef = useRef<FormInstance>();

  const onSubmit = useCallback(async () => {
    const fields = await formRef.current?.validateFields();
    const params = { ...data, ...fields };
    submitLoading?.();
    try {
      /* 编辑*/
      if (data) {
        await editService(params)
      } else {
        await addService(params);
      }
      onSuccess?.();
      closeModal?.();
      message.success('保存成功');
    }
    catch (e) {
      message.error(e.message || '保存失败');
    }
    submitStop?.();
  },[])

  useEffect(() => {
    listenOk?.(onSubmit);
  }, []);


  return (
    <FormPro
      formList={formList}
      initialValues={data}
      ref={(e: FormInstance) => (
        formRef.current = e
      )}
    />
  );
};

export default (props: ProxyProps) => {
  const { children, data } = props;
  return (
    <ModalPro
      width="100vw"
      children={children}
      title={`${data ? '编辑' : '新建'}文章`}
      triggerContent={<EditPage {...props} />}
    />
  );
}
